const { noticeApi } = require('../../../../utils/api');

Page({
  data: {
    myNotices: [],
    filteredNotices: [],
    loading: false,
    error: null,
    searchKeyword: '',
    currentUserId: 1 // 默认1，后续自动获取
  },

  onLoad() {
    // 自动获取当前登录用户id
    const userId = wx.getStorageSync('userId') || 1;
    this.setData({ currentUserId: Number(userId) });
    this.loadMyNotices();
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadMyNotices();
  },

  // 加载我发布的通知
  async loadMyNotices() {
    this.setData({ loading: true, error: null });
    
    try {
      const myNotices = await noticeApi.getMyNotices(this.data.currentUserId);
      console.log('获取我发布的通知成功:', myNotices);
      
      // 处理通知数据，添加格式化时间等
      const processedNotices = myNotices.map(notice => ({
        ...notice,
        formattedTime: this.formatTime(notice.createTime)
      }));
      
      this.setData({ 
        myNotices: processedNotices,
        filteredNotices: processedNotices,
        loading: false 
      });
      
      // 应用当前筛选
      this.applyFilter();
    } catch (error) {
      console.error('获取我发布的通知失败:', error);
      this.setData({ 
        error: '加载失败，请重试',
        loading: false 
      });
      
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  // 格式化时间
  formatTime(dateString) {
    if (!dateString) return '';
    
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    
    // 小于1分钟
    if (diff < 60000) {
      return '刚刚';
    }
    // 小于1小时
    if (diff < 3600000) {
      return Math.floor(diff / 60000) + '分钟前';
    }
    // 小于1天
    if (diff < 86400000) {
      return Math.floor(diff / 3600000) + '小时前';
    }
    // 小于7天
    if (diff < 604800000) {
      return Math.floor(diff / 86400000) + '天前';
    }
    
    // 超过7天显示具体日期
    return date.toLocaleDateString();
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({ searchKeyword: keyword });
    this.applyFilter();
  },

  // 清除搜索
  clearSearch() {
    this.setData({ searchKeyword: '' });
    this.applyFilter();
  },

  // 应用筛选
  applyFilter() {
    const { myNotices, searchKeyword } = this.data;
    let filtered = [...myNotices];

    // 搜索筛选
    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase();
      filtered = filtered.filter(notice => 
        notice.title.toLowerCase().includes(keyword) ||
        notice.content.toLowerCase().includes(keyword)
      );
    }

    // 按时间排序（置顶的在前，然后按时间倒序）
    filtered.sort((a, b) => {
      if (a.isTop !== b.isTop) {
        return b.isTop - a.isTop; // 置顶的在前
      }
      return new Date(b.createTime) - new Date(a.createTime); // 时间倒序
    });

    this.setData({ filteredNotices: filtered });
  },

  // 点击通知项
  onNoticeTap(e) {
    const { noticeId } = e.currentTarget.dataset;
    console.log('点击通知ID:', noticeId);
    
    // 根据ID查找通知详情
    const notice = this.data.filteredNotices.find(n => n.noticeId == noticeId);
    if (notice) {
      wx.showModal({
        title: notice.title,
        content: notice.content,
        showCancel: false,
        confirmText: '知道了'
      });
    }
  },

  // 创建通知
  createNotice() {
    wx.navigateTo({
      url: '/pages/class/notice/create-notice/index'
    });
  },

  // 编辑通知
  editNotice(e) {
    const { noticeId } = e.currentTarget.dataset;
    console.log('编辑通知ID:', noticeId);
    
    wx.showModal({
      title: '编辑通知',
      content: '编辑功能开发中',
      showCancel: false
    });
  },

  // 删除通知
  deleteNotice(e) {
    const { noticeId } = e.currentTarget.dataset;
    console.log('删除通知ID:', noticeId);
    
    // 根据ID查找通知详情
    const notice = this.data.filteredNotices.find(n => n.noticeId == noticeId);
    if (notice) {
      wx.showModal({
        title: '确认删除',
        content: `确定要删除通知"${notice.title}"吗？`,
        success: (res) => {
          if (res.confirm) {
            this.confirmDelete(notice);
          }
        }
      });
    }
  },

  // 确认删除
  async confirmDelete(notice) {
    try {
      await noticeApi.deleteNotice(notice.noticeId);
      wx.showToast({
        title: '删除成功',
        icon: 'success'
      });
      // 重新加载数据
      this.loadMyNotices();
    } catch (error) {
      console.error('删除通知失败:', error);
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadMyNotices().then(() => {
      wx.stopPullDownRefresh();
    }).catch((error) => {
      console.error('下拉刷新失败:', error);
      wx.stopPullDownRefresh();
    });
  }
});
